package com.ch.forum.utils;

import com.ch.forum.constants.HttpConstants;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtils {

    /**
     * 使用Get方式获取数据
     *
     * @param url
     *            URL包括参数，http://HOST/XX?XX=XX&XXX=XXX
     * @param charset
     * @return
     */
    public static String sendGet(String url, String charset) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        URL realUrl = null;
        URLConnection connection = null;
        String line;
        try {
            realUrl = new URL(url);
            // 打开和URL之间的连接
            connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty(HttpConstants.REQUEST_ACCEPT,
                    HttpConstants.REQUEST_ACCEPT_VALUE);
            connection.setRequestProperty(HttpConstants.REQUEST_CONNECTION,
                    HttpConstants.REQUEST_CONNECTION_VALUE);
            connection.setRequestProperty(HttpConstants.REQUEST_USER_AGENT,
                    HttpConstants.REQUEST_USER_AGENT_VALUE);
            connection.setRequestProperty(HttpConstants.REQUEST_CONTENT_TYPE,HttpConstants.REQUEST_CONTENT_TYPE_VALUE);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),
                    StringUtils.isEmpty(charset) ? "utf-8" : charset));
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * POST请求，字符串形式数据
     * @param url 请求地址
     * @param param 请求数据
     * @param charset 编码方式
     */
    public static String sendPostUrlParam(String url, String param, String charset) {

        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        String line;
        URL realUrl;
        URLConnection conn;
        try {
            realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty(HttpConstants.REQUEST_ACCEPT,
                    HttpConstants.REQUEST_ACCEPT_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_CONNECTION,
                    HttpConstants.REQUEST_CONNECTION_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_USER_AGENT,
                    HttpConstants.REQUEST_USER_AGENT_VALUE);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * POST请求，Map形式数据
     * @param url 请求地址
     * @param param 请求数据
     * @param charset 编码方式
     */
    public static String sendPostMapParam(String url, Map<String, String> param,
                                          String charset) {

        StringBuilder buffer = new StringBuilder();
        if (param != null && !param.isEmpty()) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                buffer.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue()))
                        .append("&");

            }
        }
        buffer.deleteCharAt(buffer.length() - 1);

        PrintWriter out = null;
        BufferedReader in = null;
        URL realUrl;
        URLConnection conn;
        String line;
        StringBuilder result = new StringBuilder();
        try {
            realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty(HttpConstants.REQUEST_ACCEPT,
                    HttpConstants.REQUEST_ACCEPT_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_CONNECTION,
                    HttpConstants.REQUEST_CONNECTION_VALUE);
            conn.setRequestProperty(HttpConstants.REQUEST_USER_AGENT,
                    HttpConstants.REQUEST_USER_AGENT_VALUE);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(buffer);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
}
